//
//  SHOriginalSectionPictureView.swift
//  SHWeibo
//
//  Created by jingming wang on 16/7/29.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit

// cell 可重用标识
private let reuseIdentifier = "pictureViewCellId"
// cell间距
let cellMargin: CGFloat = 5
// cell宽高
let cellWH: CGFloat = 80

class SHPictureView: UICollectionView {
    
    // 数据模型
    var pictuerModels: [SHPictureModel]? {
        didSet {
            // 获取当前配图的size
            let size = getPicetureViewSize(pictuerModels?.count ?? 0)
            // 更新当前配图的约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
                
            }
            // 刷新UI
            reloadData()
        }
    }
    
    // MARK: - 计算配图size
    func getPicetureViewSize(count: Int) -> CGSize {
        
        //计算行数和列数
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        //计算宽高
        let width = CGFloat(col) * cellWH + CGFloat(col - 1)*cellMargin
        let height = CGFloat(row) * cellWH + CGFloat(row - 1)*cellMargin
        
        return CGSize(width: width, height: height)
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.clearColor()
        
        // 获取layout
        let layout = self.collectionViewLayout as!UICollectionViewFlowLayout
        // 设置itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置水平和垂直间距
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        // 注册cell
        registerClass(SHPictureViewCell.self, forCellWithReuseIdentifier:reuseIdentifier)
        // 设置数据源代理
        dataSource = self
    }
}

// MARK: - dataSource
extension SHPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictuerModels?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SHPictureViewCell
        // cell赋值
        cell.pic_url = pictuerModels![indexPath.item]
        collectionView.backgroundColor = cell.contentView.backgroundColor
        return cell
    }
    
}



